package com.watchmen.mini.common.utils;

import com.watchmen.mini.common.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtil {
	private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    public static final String KEY_PREFIX = Global.getConfig("keyPrefix");
	@Autowired
	private RedisTemplate<Serializable, Object> redisTemplate;

    //设置key前缀，避免多个系统中可以重复，造成数据错误
    private static String setPrefix(String key) {
        key = KEY_PREFIX + "_" + key;
        return key;
    }

	/**
	 * 批量删除对应的value
	 * 
	 * @param keys
	 */
	public void remove(final String... keys) {
		for (String key : keys) {
            key = setPrefix(key);
			remove(key);
		}
	}

	/**
	 * 批量删除key
	 * 
	 * @param pattern
	 */
	public void removePattern(final String pattern) {
		Set<Serializable> keys = redisTemplate.keys(pattern);
		if (keys.size() > 0)
			redisTemplate.delete(keys); 
	}

	/**
	 * 删除对应的value
	 * 
	 * @param key
	 */
	public void remove(String key) {
        key = setPrefix(key);
		if (exists(key)) {
			redisTemplate.delete(key);
		}
	} 
	/**
	 * 判断缓存中是否有对应的value
	 * 
	 * @param key
	 * @return
	 */
	public boolean exists(String key) {
		return redisTemplate.hasKey(key);
	}

	/**
	 * 读取缓存
	 * 
	 * @param key
	 * @return
	 */
	public Object get(String key) {
        key = setPrefix(key);
		Object result = null;
		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
		result = operations.get(key);
		return result;
	}

	/**
	 * 写入缓存
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(String key, Object value) {
        key = setPrefix(key);
		boolean result = false;
		try { 
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			result = true;
		} catch (Exception e) {
			logger.error("set cache error", e);
		}
		return result;
	}

	/**
	 * 写入缓存
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(String key, Object value, Long expireTime) {
        key = setPrefix(key);
		boolean result = false;
		try {
			ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
			operations.set(key, value);
			redisTemplate.expire(key, expireTime, TimeUnit.MINUTES); 
			result = true;
		} catch (Exception e) {
			logger.error("set cache error", e);
		}
		return result;
	} 

	public long increment(String key, long delta) {
        key = setPrefix(key);
		return redisTemplate.opsForValue().increment(key, delta);
	}

	public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}


    /**
     * @Author Gapenne
     * @Description 根据key获取过期时间
     * @Date  2018/11/12 11:50
     * @Param [key]
     * @return java.lang.Long
     **/
    public Long getExpire(String key){
        key = setPrefix(key);
        Long timeOut = redisTemplate.getExpire(key);
        return timeOut;
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Set<Serializable> getUserKeys(String key) {
        if(StringUtils.isBlank(key)){
            key = setPrefix(key);
            Set<Serializable> allkeys = new HashSet<Serializable>();
            Set<Serializable> pcKeys = redisTemplate.keys(key+"pc_*");
            Set<Serializable> mobileKeys = redisTemplate.keys(key+"mobile_*");
            allkeys.addAll(pcKeys);
            allkeys.addAll(mobileKeys);
            return allkeys;
        }else{
            key = setPrefix(key);
            Set<Serializable> keys = redisTemplate.keys(key+"_*");
            return keys;
        }
    }

}